import { Col, Descriptions, Row, Table, Tag, Typography, Tabs, Button, message } from 'antd';
import React from 'react';
import startsWith from 'lodash/startsWith';
import forEach from 'lodash/forEach';
import CodeEditor from '@/components/CodeEditor';
import { columns, createHeadersDataSource, MethodTagColors } from './HttpCallTaskContent';
import { DataSourceType } from '../settings';
import useCopyToClipboard from '@/hooks/useCopyToClipboard';

const { TabPane } = Tabs;
const { Text } = Typography;

function formatToCopyText(headers) {
  const lines = [];
  forEach(headers, (headerValues, headerName) => {
    headerValues.forEach(headerValue => {
      lines.push(`${headerName}:${headerValue}`);
    });
  });
  return lines.join('\n');
}

function DataSourceContent({ dataSourceType, content }) {
  const { method, url, headers, body, bodyFormat } = content;

  const index = window.location.href.indexOf('/tangram/index.html');
  const baseUrl = window.location.href.substring(0, index);

  const requestUrl = startsWith(url, 'http') ? url : baseUrl + url;
  const [_state, copyToClipboard] = useCopyToClipboard();

  return (
    <>
      {dataSourceType === DataSourceType.HTTP && (
        <Descriptions column={4}>
          <Descriptions.Item label="请求地址" span={4}>
            <Tag color={`#${MethodTagColors[method]}`}>{method}</Tag>{' '}
            <Text copyable>{requestUrl}</Text>
          </Descriptions.Item>
        </Descriptions>
      )}
      <Row gutter={16}>
        <Col span={12}>
          <Tabs defaultActiveKey="body">
            <TabPane tab="Body" key="body">
              <CodeEditor readOnly mode={bodyFormat} data={body} height={550} />
            </TabPane>
            {dataSourceType === DataSourceType.HTTP && (
              <TabPane tab="Header" key="header">
                <Table
                  columns={columns}
                  dataSource={createHeadersDataSource(headers)}
                  pagination={false}
                  bordered
                />
                <Button
                  onClick={() => {
                    copyToClipboard(formatToCopyText(headers));
                    message.success('复制成功');
                  }}
                  className="margin-top"
                  icon="copy"
                  ghost
                  type="primary"
                >
                  复制Header
                </Button>
              </TabPane>
            )}
          </Tabs>
        </Col>
      </Row>
    </>
  );
}

export default DataSourceContent;
